package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstants;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * 验证码控制层
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;

    /**
     * 发送短信验证码
     */
    @PostMapping("/send4Order")
    public Result send4Order(String telephone) {
        //调用阿里大于发送短信验证码
        try {
            Integer code = ValidateCodeUtils.generateValidateCode(4);

            //先注释掉
            if (false) {
                SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code.toString());
            }

            //调试用~~~~~~~~~~~~~~~~
            System.out.println("*******发送的手机验证码为：" + code + "  *******");
            //将验证码存入Redis
            jedisPool.getResource().setex(telephone+RedisMessageConstant.SENDTYPE_ORDER, 5 * 60, code.toString());
            //返回结果
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    @PostMapping("/send4Login")
    public Result send4Login(String telephone) {
        //调用阿里大于发送验证码
        try {
            String validateCode4String = ValidateCodeUtils.generateValidateCode4String(4);
            if (false) {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, validateCode4String);
            }
            //调试用~~~~~~~~~~~~~~~~
            System.out.println("*******发送的手机验证码为：" + validateCode4String + "  *******");
        //将验证码存入Redis
            jedisPool.getResource().setex(RedisMessageConstant.SENDTYPE_LOGIN+telephone, 60*5,validateCode4String);
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

}
